﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Novel.Server.Models;
using Novel.Server.Response;

namespace Novel.Server.Controllers
{
    /// <summary>
    /// 负责显示图片
    /// </summary>
    [Route("api/favorites")]
    [ApiController]
    public class FavoriteController : ControllerBase
    {
        private readonly NovelContext dbContext;
        private readonly IConfiguration conf;

        public FavoriteController(NovelContext context, IConfiguration configuration)
        {
            dbContext = context;
            conf = configuration;
        }

        /// <summary>
        /// 将一本书加入收藏
        /// </summary>
        [HttpPut("{novelId}")]
        [Authorize]
        public async Task<IActionResult> AddFavorite(int novelId)
        {
            var username = User.Identity?.Name;
            var user = await dbContext.Users.FirstOrDefaultAsync(u => u.Username == username && !u.IsDeleted);
            if (user == null)
                return Unauthorized(ApiResponse.ErrorResponse("用户不存在", 401));

            var novelExists = await dbContext.Novels.AnyAsync(n => n.NovelId == novelId && !n.IsDeleted);
            if (!novelExists)
                return NotFound(ApiResponse.ErrorResponse("小说不存在", 404));


            var exists = await dbContext.Favorites
                .AnyAsync(f => f.UserId == user.UserId && f.NovelId == novelId);

            if (!exists)
            {

                dbContext.Favorites.Add(new Favorite
                {
                    UserId = user.UserId,
                    NovelId = novelId,
                    CreatedAt = DateTime.Now
                });

                await dbContext.SaveChangesAsync();
            }

            return Ok(ApiResponse.SuccessResponse(true));
        }

        /// <summary>
        /// 将一本书从收藏中移除
        /// </summary>
        [HttpDelete("{novelId}")]
        [Authorize]
        public async Task<IActionResult> RemoveFavorite(int novelId)
        {
            var username = User.Identity?.Name;
            var user = await dbContext.Users.FirstOrDefaultAsync(u => u.Username == username && !u.IsDeleted);
            if (user == null)
                return Unauthorized(ApiResponse.ErrorResponse("用户不存在", 401));

            var fav = await dbContext.Favorites
                .FirstOrDefaultAsync(f => f.UserId == user.UserId && f.NovelId == novelId);

            if (fav != null)
            {
                dbContext.Favorites.Remove(fav);
                await dbContext.SaveChangesAsync();
            }

            return Ok(ApiResponse.SuccessResponse(true));
        }

    }
}

